<script setup lang="ts">
import { computed, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import BigNumber from 'bignumber.js'
import { get } from 'lodash-es'
import user from '@/composables/user'
import { getPaymentRecordList } from '@/api/pay'
import { queryUserInfo } from '@/api/user'
import { toast } from '@/utils/utils'
import type { QueryUserInfoDto } from '@/api/user/type'
import type { PaymentRecordDto } from '@/api/pay/type'

interface MenuItem {
    icon: string
    text: string
    path: string
    hide?: boolean
    disable?: boolean
    callback?: () => void
}

const statusBarHeight = ref(0)
const menu = ref<MenuItem[]>(
    [{
        icon: '../../static/images/mine/icon-message.png',
        text: '订阅消息',
        path: '/pages/record/record',
        disable: false,
        callback: () => {
            if (!user.isLogin.value) {
                toast('登录后即可订阅')
                return
            }
            onSubscribe()
        },
    }, {
        icon: '../../static/images/mine/icon-assitant.png',
        text: '客服助手',
        path: '/pages/my-sign-up/my-sign-up',
        disable: false,
        hide: false,
        callback: () => {
            uni.navigateTo({
                url: '/package-mine/pages/service/service',
            })
        },
    }, {
        icon: '../../static/images/mine/icon-setting.png',
        text: '账户设置',
        path: '/packageAdvance/pages/advance-index/advance-index',
        callback: () => {
            uni.navigateTo({
                url: '/package-mine/pages/account-setting/account-setting',
            })
        },
    }],
)

const totalRevenue = ref(0)
const toBePaid = ref(0)

const showHints = ref(false)

const queryData = ref<QueryUserInfoDto>({} as QueryUserInfoDto)

const shortName = computed(() => {
    if (!user.userInfo.value.userName?.length)
        return ''
    return user.userInfo.value.userName?.length > 2 ? user.userInfo.value.userName.slice(user.userInfo.value.userName.length - 2) : user.userInfo.value.userName.slice(user.userInfo.value.userName.length - 1)
})

function onToInfo(item: MenuItem) {
    if (item.disable)
        toast('功能开发中')
    else
        item.callback?.()
}

/**
 * 跳转到薪资页面
 *
 * @returns 无返回值
 */
function toSalary() {
    uni.navigateTo({
        url: '/package-mine/pages/salary/salary',
    })
}

/**
 * 跳转到登录页面
 *
 * @returns 无返回值
 */
function onToLogin() {
    uni.navigateTo({
        url: '/pages/login/login',
    })
}

/**
 * 跳转到个人信息页面
 *
 * @returns 无返回值
 */
function toPersonalInfo() {
    uni.navigateTo({
        url: '/package-mine/pages/personal-info/personal-info',
    })
}

/**
 * 获取当前用户信息
 *
 * @returns 返回查询结果
 */
async function getQueryData() {
    const res = await queryUserInfo()
    queryData.value = res
}

async function getList() {
    const res = await getPaymentRecordList({})
    return res
}

/**
 * 计算总收入和待领取
 *
 * @param res 计算参数，包括记录列表和总金额
 * @param res.record 支付记录列表
 * @param res.totalMoney 总金额
 * @returns 无返回值
 */
function calcValue(res: {
    record: PaymentRecordDto[]
    totalMoney: number
}) {
    totalRevenue.value = res?.totalMoney
    toBePaid.value = res?.record?.reduce((prev, next) => {
        return Number(new BigNumber(prev || 0).plus(new BigNumber(next.paymentAmount || 0)))
    }, 0)
}
function onTorecord() {
    uni.navigateTo({
        url: '/package-mine/pages/record/record',
    })
}

function onTopayrollList() {
    uni.navigateTo({
        url: '/package-mine/pages/payroll-list/payroll-list',
    })
}

function onToMySignUp() {
    uni.navigateTo({
        url: '/package-mine/pages/my-sign-up/my-sign-up',
    })
}
function onToAdvance() {
    uni.navigateTo({
        url: '/package-advance/pages/advance-index/advance-index',
    })
}

function onCloseHint() {
    showHints.value = false
}

async function onSubscribe() {
    const res = await my.requestSubscribeMessage({
        entityIds: [
            // 'd413dbff63b643be876bcfd8ba6c5ece', // 一次性
            '3bdfed49c73549e4bc77095487cb42f3', // 长期
        ],
    })
    if (res.success)
        toast('您已订阅消息')
}

onPullDownRefresh(async () => {
    await user.login().catch(() => {
        uni.stopPullDownRefresh()
    })
    const res = await getList()
    calcValue(res)
    getQueryData()
    uni.stopPullDownRefresh()
})

onShow(async () => {
    // #ifdef MP-ALIPAY
    my.setNavigationBar({
        frontColor: '#ffffff',
        backgroundColor: '#ffffff',
    })
    // #endif
    const instance = getCurrentInstance()
    const scope = get(instance, 'proxy.$scope', {}) as AnyObject
    if (typeof scope.getTabBar === 'function' && scope?.getTabBar()) {
        scope.getTabBar().setData({
            selected: 2,
        })
    }

    statusBarHeight.value = uni.getWindowInfo().statusBarHeight
    await user.waitLogin()

    showHints.value = !user.userInfo.value.userHeadUrl

    if (user.isLogin.value) {
        const res = await getList()
        calcValue(res)
        getQueryData()
    }
})
</script>

<template>
    <view>
        <view class="set-bg box-border rounded-lb-32rpx rounded-rb-32rpx px-60rpx"
              :style="{ paddingTop: `${statusBarHeight * 2}px` }">
            <view v-if="!user.isLogin.value" class="mt-30rpx flex items-center" @click="onToLogin">
                <img class="mr-20px h-70rpx w-70rpx rounded-full" src="../static/images/mine/default-head.png" alt="">
                <view class="text-white font-bold">
                    未登录 立即登录
                </view>
            </view>
            <view v-else class="mt-30rpx flex items-center" @click="toPersonalInfo">
                <img v-if="user.userInfo.value.userHeadUrl" class="mr-10px h-70rpx w-70rpx rounded-full"
                     :src="user.userInfo.value.userHeadUrl" alt="">
                <view v-else class="mr-10rpx h-64rpx w-64rpx flex items-center justify-center rounded-full bg-#bcd9ff">
                    <view class="text-xs text-white">
                        {{ shortName }}
                    </view>
                </view>
                <view class="flex items-center text-white font-bold">
                    <view>{{ user.userInfo.value.userName }}</view>
                    <image class="ml-8rpx h-28rpx w-28rpx" src="../../static/images/arrow-go.png" />
                </view>
                <view v-if="showHints"
                      class="relative rounded-10rpx bg-#202536 px-25rpx py-15rpx text-white before:absolute before:top-10rpx before:h-0 before:w-0 before:border-20rpx before:border-b-transparent before:border-l-transparent before:border-r-#202536 before:border-t-transparent before:border-solid before:content-empty before:-left-30rpx">
                    <view>点击修改个人信息<text class="pl-10rpx text-#888B94" @click.stop="onCloseHint">×</text></view>
                </view>
            </view>
            <view class="flex items-center justify-between -mt-10rpx">
                <view>
                    <view class="text-xs text-white text-opacity-50 font-bold">
                        总收入（元）
                    </view>
                    <view class="mt-10rpx text-72rpx text-white font-bold">
                        {{ totalRevenue }}
                    </view>
                </view>
                <view class="bg-ball flex flex-col items-center justify-center text-white" @click="toSalary">
                    <view class="text-xs">
                        待领取
                    </view>
                    <view class="my-16rpx flex items-end">
                        <view class="mb-6rpx text-x2s">
                            ¥
                        </view>
                        <view class="text-x2l font-bold">
                            {{ toBePaid }}
                        </view>
                    </view>
                    <view class="w-100rpx rounded-full bg-#E66918 py-10rpx text-center text-xs">
                        领取
                    </view>
                </view>
            </view>
        </view>
        <view class="px-32rpx -mt-80rpx">
            <view class="set-bg2 mt-30rpx flex justify-between rounded-16rpx px-40rpx py-52rpx">
                <view class="text-center" @click="onTorecord">
                    <view class="text-44rpx font-bold">
                        {{ queryData.workCount || 0 }}
                    </view>
                    <view class="mt-24rpx text-28rpx text-gray font-bold">
                        工作记录
                    </view>
                </view>
                <view class="text-center" @click="onToMySignUp">
                    <view class="text-44rpx font-bold">
                        {{ queryData.jobCount || 0 }}
                    </view>
                    <view class="mt-24rpx text-28rpx text-gray font-bold">
                        我的报名
                    </view>
                </view>
                <view class="text-center" @click="onToAdvance">
                    <view class="text-44rpx font-bold">
                        <text class="text-sm text-#565868 font-normal">
                            ¥
                        </text>
                        <text>{{ queryData.advanceAmount || 0 }}</text>
                    </view>
                    <view class="mt-24rpx text-28rpx text-gray font-bold">
                        我的预支
                    </view>
                </view>
                <view class="text-center" @click="onTopayrollList">
                    <view class="text-44rpx font-bold">
                        <text>{{ queryData.stubCount || 0 }}</text>
                        <text class="text-sm text-#565868 font-normal">
                            条
                        </text>
                    </view>
                    <view class="mt-24rpx text-28rpx text-gray font-bold">
                        工资单
                    </view>
                </view>
            </view>

            <!-- 暂时隐藏掉，后面版本会放开，从支付宝接口里获取 -->
            <view v-if="false" class="set-bg3 mt-24rpx flex items-center justify-between rounded-2xl px-24rpx py-32rpx">
                <view class="flex">
                    <img class="mr-24rpx h-66rpx w-66rpx" src="../../static/images/mine/icon-person-info.png" alt="">
                    <view>
                        <view class="text-base">
                            资料完整度0%
                        </view>
                        <view class="mt-10rpx text-xs text-lightgray">
                            芝麻工作证一键认证
                        </view>
                    </view>
                </view>
                <view>
                    <view class="set-bg4 rounded-full px-24rpx py-12rpx text-xs color-#3E5FF5">
                        <text>实名认证</text>
                    </view>
                </view>
            </view>

            <view class="set-shadow mt-24rpx rounded-2xl bg-white bg-white">
                <template v-for="(item, index) in menu" :key="index">
                    <view v-if="!item.hide" class="flex justify-between p-40rpx" @click="onToInfo(item)">
                        <view class="flex items-center gap-24rpx">
                            <img class="h-48rpx w-48rpx" :src="item.icon" alt="">
                            <view class="text-32rpx">
                                {{ item.text }}
                            </view>
                        </view>
                        <view class="flex items-center gap-10rpx">
                            <img class="h-48rpx w-48rpx" src="../static/images/mine/arrow.png" alt="">
                        </view>
                    </view>
                </template>
            </view>
            <!-- <view @click="onSubscribe">订阅</view> -->
        </view>
    </view>
</template>

<style scoped>
.set-bg {
    background: url('https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager363631e9-06ab-476d-890f-a9978e34dd83.png') no-repeat;
    height: 600rpx;
}

.bg-ball {
    background: url('https://bullet001.oss-cn-shanghai.aliyuncs.com/file/blueUser2a60a566-4344-4c49-b633-206075f26fab.png') no-repeat;
    background-size: contain;
    width: 300rpx;
    height: 300rpx;
    margin-right: -20rpx;
}

.set-bg2 {
    background: radial-gradient(45% 50% at 94% 0%, #DAE6FF 0%, rgba(224, 234, 255, 0) 100%), linear-gradient(146deg, #FFEFE1 0%, #FFFEFE 11%, #FFFFFF 89%);
}

.set-bg3 {
    background: linear-gradient(101deg, #EAF2FD 15%, #F3F1FE 99%);
}

.set-bg4 {
    background: linear-gradient(112deg, #FFFFFF 13%, #E5EAFA 87%);
}

.set-shadow {
    box-shadow: 0px 8px 16px 0px rgba(232, 239, 253, 0.5);
}
</style>

<route lang="json">
{
    "style": {
        "navigationBarTextStyle": "white",
        "mp-alipay": {
            "transparentTitle": "always"
        },
        "enablePullDownRefresh": true
    }
}
</route>
